package com.halflife.websocket.client;

import com.alibaba.fastjson.JSON;
import com.halflife.websocket.entity.Client;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.handler.stream.ChunkedWriteHandler;
import java.net.URI;

public class WebSocketNettyClient {

    public static void main(String[] args)  {

        EventLoopGroup group = new NioEventLoopGroup();
        final ClientHandler handler =new ClientHandler();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group).channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 添加一个http的编解码器
                            pipeline.addLast(new HttpClientCodec());
                            // 添加一个用于支持大数据流的支持
                            pipeline.addLast(new ChunkedWriteHandler());
                            // 添加一个聚合器，这个聚合器主要是将HttpMessage聚合成FullHttpRequest/Response
                            pipeline.addLast(new HttpObjectAggregator(65536));
                            pipeline.addLast(handler);

                        }
                    });

            URI websocketURI = new URI("ws://192.168.1.3:5000?id=1&roomId=12");
            HttpHeaders httpHeaders = new DefaultHttpHeaders();
            //进行握手
            WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(websocketURI, WebSocketVersion.V13, (String)null, true,httpHeaders,Integer.MAX_VALUE);
            ChannelFuture connectFuture = bootstrap.connect(websocketURI.getHost(), websocketURI.getPort());
            final Channel channel=connectFuture.sync().channel();
            handler.setHandshaker(handshaker);
            ChannelFuture handshakeFugture = handshaker.handshake(channel);
            //阻塞等待是否握手成功
            ChannelFuture rFuture = handshakeFugture.sync();
            if (rFuture.cause() != null) {
                 rFuture.cause().printStackTrace();
            }
            System.out.println("握手成功");

            //发送消息
            String name = JSON.toJSONString(Client.getFileInstance());
            ChannelFuture writeFuture = channel.writeAndFlush(new TextWebSocketFrame(name)).sync();
            if (writeFuture.isSuccess()) {
                System.out.println("成功："+writeFuture.get());
            }

             writeFuture = channel.writeAndFlush(new TextWebSocketFrame(name)).sync();
            if (writeFuture.isSuccess()) {
                System.out.println("成功："+writeFuture.get());
            }
            // 等待连接被关闭
            channel.closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            group.shutdownGracefully();
        }

    }

}